/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.ems.web;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.constant.Constant;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.IdGen;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.cms.entity.Comment;
import com.thinkgem.jeesite.modules.cms.entity.Site;
import com.thinkgem.jeesite.modules.cms.utils.CmsUtils;
import com.thinkgem.jeesite.modules.ems.entity.Award;
import com.thinkgem.jeesite.modules.ems.entity.Course;
import com.thinkgem.jeesite.modules.ems.service.AwardService;
import com.thinkgem.jeesite.modules.ems.service.CourseService;
import com.thinkgem.jeesite.modules.ems.service.JoinService;
import com.thinkgem.jeesite.modules.ems.service.OrderService;
import com.thinkgem.jeesite.modules.sys.entity.Dict;
import com.thinkgem.jeesite.modules.sys.entity.Mdict;
import com.thinkgem.jeesite.modules.sys.service.DictService;
import com.thinkgem.jeesite.modules.sys.service.MdictService;

/**
 * 奖品管理Controller
 * @author zad
 * @version 2017-10-23
 */
@Controller
@RequestMapping(value = "${adminPath}/ems/award")
public class AwardController extends BaseController {

	@Autowired
	private AwardService awardService;
	@Autowired
	private CourseService courseService;
	
	@Autowired
	private JoinService joinService;
	
	@Autowired
	private MdictService mdictService;
	
	@Autowired
	private DictService dictService;
	
	@Autowired
	private OrderService orderService;
	
	@ModelAttribute
	public Award get(@RequestParam(required=false) String id) {
		Award entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = awardService.get(id);
		}
		if (entity == null){
			entity = new Award();
		}
		return entity;
	}
	
	@RequiresPermissions("ems:award:view")
	@RequestMapping(value = {"list", ""})
	public String list(Award award, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Award> page = awardService.findPage(new Page<Award>(request, response), award); 
		model.addAttribute("page", page);
		return "modules/ems/awardList";
	}

	@RequiresPermissions("ems:award:view")
	@RequestMapping(value = "form")
	public String form(Award award, Model model) {
		model.addAttribute("award", award);
		
		Course course = new Course();
		// course.setId(award.getCourse().getId());
		List<Course> courses = this.courseService.findList(course);
		
		model.addAttribute("courses", courses);
		
		// 查询大类列表
		Mdict mdict = new Mdict();
		if(null != award.getCourse())
		{
			
			mdict.setType(Constant.Mdict.MDICT_COURSE_TYPE_PREFIX + award.getCourse().getSign());
			List<Mdict> bigCategories = this.mdictService.findList(mdict);
			model.addAttribute("bigCategories", bigCategories);
		}
		// 查询小类列表
		mdict.setType(mdict.getType() + "_" + award.getBigCategory());
		List<Mdict> smallCategories = this.mdictService.findList(mdict);
		
		
		model.addAttribute("smallCategories", smallCategories);
		
		
		return "modules/ems/awardForm";
	}

	@RequiresPermissions("ems:award:edit")
	@RequestMapping(value = "save")
	public String save(Award award, Model model, RedirectAttributes redirectAttributes) throws Throwable{
		if (!beanValidator(model, award)){
			return form(award, model);
		}
		
		
		//awardService.save(award);
		// 将多个选手名称及对应id转换为list，用用后台批量插入
		awardService.parseJionList(award);
		
		if(award.getJoinerList().size()>1)
		{
			int rows = awardService.saveBatch(award);
			System.out.println("后台插入奖品信息：奖品来源："+award.getAwardFrom()+"家长手机号："+award.getMobile()+",报名人数：" + award.getJoinerList().size() +",插入奖品信息条数：" + rows + "录入的所有选手姓名：" + award.getJoiner());
			logger.info("后台插入奖品信息：奖品来源："+award.getAwardFrom()+"家长手机号："+award.getMobile()+",报名人数：" + award.getJoinerList().size()+",插入奖品信息条数：" + rows + "录入的所有选手姓名：" + award.getJoiner());
			if(rows < 1)
			{
				throw new Exception("插入奖品信息条数为0");
			}
		}
		else
		{
			awardService.save(award);
		}
		
		addMessage(redirectAttributes, "保存奖品成功");
		return "redirect:"+Global.getAdminPath()+"/ems/award/?repage";
	}
	
	@RequiresPermissions("ems:award:edit")
	@RequestMapping(value = "delete")
	public String delete(Award award, RedirectAttributes redirectAttributes) {
		awardService.delete(award);
		addMessage(redirectAttributes, "删除奖品成功");
		return "redirect:"+Global.getAdminPath()+"/ems/award/?repage";
	}
	
	
	@RequiresPermissions("ems:batch:import")
	@RequestMapping(value = {"batchImport"})
	public String batchImport(Comment comment, HttpServletRequest request, HttpServletResponse response, Model model) {
        /*Page<Comment> page = commentService.findPage(new Page<Comment>(request, response), comment); 
        model.addAttribute("page", page);
		return "modules/cms/commentList";*/
		return "modules/ems/batchImport";
	}
	
	/**
     * 奖品导入模板下载
     */
    @RequestMapping("downLoadTemplate")
    public void downLoadTemplate(HttpServletRequest request, HttpServletResponse response) throws IOException{
    	 String templatePath = request.getSession().getServletContext().getRealPath("/template");
	     // String path = templatePath+"/奖品信息导入模板.xlsx"; 
    	 String path = templatePath+"/" + Global.getConfig("batchImportTemplate"); 
    	File file = new File(path);// path是根据日志路径和文件名拼接出来的
    	if(file.exists()){
    		String filename = file.getName();// 获取日志文件名称
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            response.reset();
            // 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.replaceAll(" ", "").getBytes("utf-8"),"iso8859-1"));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream os = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            os.write(buffer);// 输出文件
            os.flush();
            os.close();
    	}else{
    		System.out.println("没有找到文件");
    	}
    
    }
    
    /**
     * 奖品信息导入
     */
    @RequiresPermissions("ems:batch:import")
	@RequestMapping(value = "import")
	public String doBatchImport(@RequestParam(value = "batchFile", required = false) MultipartFile batchFile,
			HttpServletRequest request, HttpServletResponse response, Model model) {
		// return "redirect:" + adminPath + "/cms/comment/?repage&delFlag=2";
		Site site = CmsUtils.getSite(Site.defaultSiteId());
		String msg = "";
		boolean rs = true;
		
		// 记录注册人为空的奖品数据
        // String nullRegisterMsg = null;
        
        // 记录奖品来源为空的奖品数据
        String nullAwardFromMsg = null;
        // 记录家长电话为空的奖品数据
        String nullMobileMsg = null;
        // 记录家长电话输入错误的奖品数据
        String errMobileMsg = null;
        
        
        // 选手姓名为空的奖品数据
        String nullJoinerMsg = null;
        // 选手姓名输入错误的奖品数据
        String errJoinerMsg = null;
        // 组别为空的奖品数据
        String nullGroupTypeMsg = null;
        // 展示方式为空的奖品数据
        String nullJoinTypeMsg = null;
        // 课程名称为空的奖品数据
        String nullCourseMsg = null;
        // 展示大类为空的奖品数据
        String nullBigCatMsg = null;
        // 展示小类为空的奖品数据
        String nullSmallCatMsg = null;
        // 推选学校为空的奖品数据
        String nullShoolMsg = null;
        // 奖品为空的奖品数据
        String nullAwardMsg = null;
        
        
		if (batchFile != null) {
            try {
                InputStream is = batchFile.getInputStream();
                Workbook workBook = null;
                try{
                	workBook = new XSSFWorkbook(is);
                }catch(Exception e){
                	POIFSFileSystem fs = new POIFSFileSystem(is);
                	workBook = new HSSFWorkbook(fs);
                }
                XSSFSheet sheet;// = workbook.getSheetAt(index);
                
                // for(int i = 0; i < workBook.getNumberOfSheets(); i ++){
                	sheet=(XSSFSheet)workBook.getSheetAt(0);
	                //创建行和列
	                XSSFRow row;
	                
	                int rows = sheet.getLastRowNum();
	                
	                List<Award> awardList = new ArrayList<Award>();
	                Date createDate = new Date();
	        		
	                for (int j = 1; j <= rows; j++) {
	                    row = sheet.getRow(j);
	                    // 家长姓名
	                    /*String register = null == row.getCell(0) ? null : row.getCell(0).toString().trim();
	                    if(StringUtils.isBlank(register))
	                    {
	                    	if(null == nullRegisterMsg)
	                    	{
	                    		nullRegisterMsg = "第" + (j + 1) + "行家长姓名为空";
	                    	}
	                    	else
	                    	{
	                    		nullRegisterMsg += "," + (j + 1) + "行家长姓名为空";
	                    	}
	                    	continue;
	                    }*/
	                    
	                    // 奖品来源
	                    String awardFrom = null == row.getCell(0) ? null : row.getCell(0).toString().trim();
	                    /*if(StringUtils.isBlank(awardFrom))
	                    {
	                    	if(null == nullAwardFromMsg)
	                    	{
	                    		nullAwardFromMsg = "第" + (j + 1) + "行奖品来源为空";
	                    	}
	                    	else
	                    	{
	                    		nullAwardFromMsg += "," + (j + 1) + "行奖品来源为空";
	                    	}
	                    	continue;
	                    }
	                    // 奖品来源 system：系统报名；onsite：现场报名
	                    awardFrom = "系统报名".equals(awardFrom)?"system":"onsite";*/
	                    
	                    // 家长电话
	                    String mobile = null == row.getCell(1) ? null : row.getCell(1).toString().trim();
	                    
	                    /*if(StringUtils.isBlank(mobile))
	                    {
	                    	if(null == nullMobileMsg)
	                    	{
	                    		nullMobileMsg = "第" + (j+1);
	                    	}
	                    	else
	                    	{
	                    		nullMobileMsg += "," + (j + 1);
	                    	}
	                    	continue;
	                    }
	                    if(!mobile.matches(Constant.REG_MOBILE_PATTERN))
	                    {
	                    	if(null == errMobileMsg)
	                    	{
	                    		errMobileMsg = "第" + (j+1);
	                    	}
	                    	else
	                    	{
	                    		errMobileMsg += "," + (j + 1);
	                    	}
	                    	continue;
	                    }*/
	                    
	                    // 选手姓名
	                    String joiner = null == row.getCell(2) ? null : row.getCell(2).toString().trim();
	                    if(StringUtils.isBlank(joiner))
	                    {
	                    	if(null == nullJoinerMsg)
	                    	{
	                    		nullJoinerMsg = "第" + (j+1);
	                    	}
	                    	else
	                    	{
	                    		nullJoinerMsg += "," + (j + 1);
	                    	}
	                    	continue;
	                    }
	                    
	                    // 姓名不再判断中文
	                    /*if(!joiner.matches(Constant.REG_NAME_COMMA))
	                    {
	                    	if(null == errJoinerMsg)
	                    	{
	                    		errJoinerMsg = "第" + (j+1);
	                    	}
	                    	else
	                    	{
	                    		errJoinerMsg += "," + (j + 1);
	                    	}
	                    	continue;
	                    }*/
	                    
	                    
	                    // 组别
	                    String groupType = null == row.getCell(3) ? null : row.getCell(3).toString().trim();
	                    
	                    if(StringUtils.isBlank(groupType) || "请选择组别".equals(groupType))
	                    {
	                    	if(null == nullGroupTypeMsg)
	                    	{
	                    		nullGroupTypeMsg = "第" + (j+1);
	                    	}
	                    	else
	                    	{
	                    		nullGroupTypeMsg += "," + (j + 1);
	                    	}
	                    	continue;
	                    }
	                    groupType = this.dictService.getValueByLabel(Constant.Dict.DICT_GROUP_TYPE, groupType);
	                    
	                    // 展示方式
	                    String joinType = null == row.getCell(4) ? null : row.getCell(4).toString().trim();
	                    if(StringUtils.isBlank(joinType) || "请选择展示方式".equals(joinType))
	                    {
	                    	if(null == nullJoinTypeMsg)
	                    	{
	                    		nullJoinTypeMsg = "第" + (j+1);
	                    	}
	                    	else
	                    	{
	                    		nullJoinTypeMsg += "," + (j + 1);
	                    	}
	                    	continue;
	                    }
	                    joinType = this.dictService.getValueByLabel(Constant.Dict.DICT_JOIN_TYPE, joinType);
	                    
	                    // 课程名称
	                    String courseSign = null == row.getCell(5) ? null : row.getCell(5).toString().trim();
	                    if(StringUtils.isBlank(courseSign) || "请选择课程".equals(courseSign))
	                    {
	                    	if(null == nullCourseMsg)
	                    	{
	                    		nullCourseMsg = "第" + (j+1);
	                    	}
	                    	else
	                    	{
	                    		nullCourseMsg += "," + (j + 1);
	                    	}
	                    	continue;
	                    }
	                    // 根据序号转换为相应的课程
	                    courseSign = courseSign.startsWith("英语")?Constant.Course.COURSE_SIGN_ENG:courseSign.startsWith("艺术")?Constant.Course.COURSE_SIGN_ART:Constant.Course.COURSE_SIGN_PAINT;
	                    Course course = this.courseService.get(courseSign);
	                    String courseId = course.getId();
	                    
	                    // 展示大类
	                    String bigCat = null == row.getCell(6) ? null : row.getCell(6).toString().trim();
	                    /*if(StringUtils.isBlank(bigCat))
	                    {
	                    	if(null == nullBigCatMsg)
	                    	{
	                    		nullBigCatMsg = "第" + (j+1);
	                    	}
	                    	else
	                    	{
	                    		nullBigCatMsg += "," + (j + 1);
	                    	}
	                    	continue;
	                    }*/
	                    // 当展示大类为“其他”时，进行转换
	                    bigCat = this.mdictService.getBigCatValueByLabel(Constant.Mdict.MDICT_COURSE_TYPE_PREFIX+courseSign, bigCat);
	                    
	                    
	                    // 展示小类
	                    String smallCat = null == row.getCell(7) ? null : row.getCell(7).toString().trim();
	                    // 当展示大类不是其它并且课程不是书法美术时，展示小类不能为空
	                    if(!"other".equals(bigCat) && !"paint".equals(courseSign))
	                    {
	                    	/*if("请选择小类".equals(smallCat)){
		                    	if(null == nullSmallCatMsg)
		                    	{
		                    		nullSmallCatMsg = "第" + (j+1);
		                    	}
		                    	else
		                    	{
		                    		nullSmallCatMsg += "," + (j + 1);
		                    	}
		                    	continue;
	                    	}
	                    	else
	                    	{*/
	                    		smallCat = this.mdictService.getSmallCatByLabel(Constant.Mdict.MDICT_COURSE_TYPE_PREFIX+courseSign, bigCat, smallCat);
	                    	//}
	                    }
	                    else
	                    {
	                    	smallCat = "";
	                    }
	                    
	                    // 推荐学校
	                    String school = null == row.getCell(8) ? null : row.getCell(8).toString().trim();
	                    if(StringUtils.isBlank(school))
	                    {
	                    	if(null == nullShoolMsg)
	                    	{
	                    		nullShoolMsg = "第" + (j+1);
	                    	}
	                    	else
	                    	{
	                    		nullShoolMsg += "," + (j + 1);
	                    	}
	                    	continue;
	                    }
	                    
	                    // 获得荣誉
	                    String awardInfo = null == row.getCell(9) ? null : row.getCell(9).toString().trim();
	                    if(StringUtils.isBlank(awardInfo))
	                    {
	                    	if(null == nullAwardMsg)
	                    	{
	                    		nullAwardMsg = "第" + (j + 1)/* + "行家长姓名为空"*/;
	                    	}
	                    	else
	                    	{
	                    		nullAwardMsg += "," + (j + 1)/* + "行家长姓名为空"*/;
	                    	}
	                    	continue;
	                    }
	                    
	                    // 奖品领取状态
	                    /*String status = null == row.getCell(10) ? null : row.getCell(10).toString().trim();
	                    
	                    status = "否".equals(status)?"0":"1";*/
	                    
	                    // 奖品领取备注
	                    String score = null == row.getCell(10) ? null : row.getCell(10).toString().trim();
	                    
	                    // 奖品领取备注
	                    String remarks = null == row.getCell(11) ? null : row.getCell(11).toString().trim();
	                    
	                    
	                    
	                    Award award = new Award();
	                    
	                    String id=IdGen.uuid();
	                    award.setId(id);
	                    
	                    // award.setRegister(register);
	                    
	                    award.setAwardFrom(awardFrom);
	                    award.setMobile(mobile);
	                    award.setJoiner(joiner);
	                    award.setGroupType(groupType);
	                    award.setJoinType(joinType);
	                    
	                    Course courseP = new Course();
	                    courseP.setId(courseId);
	                    award.setCourse(courseP);
	                    award.setBigCategory(bigCat);
	                    award.setSmallCategory(smallCat);
	                    award.setSchool(school);
	                    // award.setStatus(status);
	                    award.setStatus(Constant.Award.AWARD_STAUTS_YES);
	                    award.setAward(awardInfo);
	                    award.setRemarks(remarks);
	                    
	                    if(StringUtils.isBlank(score))
	                    {
	                    	score = "0.00";
	                    }
	                    award.setScore(Double.parseDouble(score));
	                    
	                    award.setCreateDate(createDate);
		        		award.setUpdateDate(createDate);
		        		
	                    // 将多个选手名称及对应id转换为list，用用后台批量插入
	            		// awardService.parseJionList(award);
	                    awardList.add(award);
	                    if(null != awardList && awardList.size() > 500)
	                    {
	                    	 this.awardService.saveList(awardList);
	                    	 awardList = new ArrayList<Award>();
	                    }
	                    
	                }
	                
	                if(null != awardList && awardList.size() > 0)
                    {
                    	 this.awardService.saveList(awardList);
                    }
	                msg = "导入成功。";
                //}
            } catch (IOException e) {
            	e.printStackTrace();
            	rs = false;
            	msg = "导入失败。" + e.getMessage();
            } catch (Exception e) {
            	rs = false;
            	msg = "导入失败。" + e.getMessage();
            	e.printStackTrace();
            }
        }
		
		/*if(null != nullRegisterMsg)
		{
			msg += nullRegisterMsg + "行家长姓名为空，不做处理; ";
		}*/
		
		/*if(null != nullAwardFromMsg)
		{
			msg += nullAwardFromMsg + "行奖品来源为空，不做处理; ";
		}
		
		
		if(null != nullMobileMsg)
		{
			msg += nullMobileMsg + "行家长电话为空，不做处理; ";
		}
		if(null != errMobileMsg)
		{
			msg += errMobileMsg + "行家长电话输入错误，不做处理; ";
		}*/
		if(null != nullJoinerMsg)
		{
			msg += nullJoinerMsg + "行选手姓名为空，不做处理; ";
		}
		if(null != errJoinerMsg)
		{
			msg += errJoinerMsg + "行选手姓名输入格式错误，不做处理; ";
		}
		if(null != nullGroupTypeMsg)
		{
			msg += nullGroupTypeMsg + "行组别为空，不做处理; ";
		}
		if(null != nullJoinTypeMsg)
		{
			msg += nullJoinTypeMsg + "行展示方式为空，不做处理; ";
		}
		if(null != nullCourseMsg)
		{
			msg += nullCourseMsg + "行课程名称为空，不做处理; ";
		}
		if(null != nullBigCatMsg)
		{
			msg += nullBigCatMsg + "行展示大类为空，不做处理; ";
		}
		if(null != nullSmallCatMsg)
		{
			msg += nullSmallCatMsg + "行展示小类为空，不做处理; ";
		}
		if(null != nullAwardMsg)
		{
			msg += nullAwardMsg + "行奖品信息为空，不做处理; ";
		}
		if(null != nullShoolMsg)
		{
			msg += nullShoolMsg + "行推荐学校为空，不做处理; ";
		}
		
		
		// request.setAttribute("msg", msg);
		model.addAttribute("msg", msg);
		model.addAttribute("rs", rs);
		// return "modules/sys/sysIndex";
		return "modules/ems/batchImport";
	}

}